package com.LeeCode;

import org.junit.jupiter.api.Test;

/**
 * 外观数列
 */

public class Code038 {
    public static void main(String[] args) {
        int n = 7;
        System.out.println(new Code038().countAndSay1(n));
    }

    public String countAndSay(int n) {
        if (n == 1) return "1";

        return encode(countAndSay(n - 1));
    }

    public String countAndSay1(int n) {
        String res = "1", pre = "1";
        for (int i = 2; i <= n; i++) {
            res = encode(pre);
            pre = res;
        }
        return res;
    }

    public String encode(String s) {
        StringBuilder sb = new StringBuilder();
        int index = 0, count = 0;
        char c = s.charAt(0);
        while (index < s.length()) {
            while (index < s.length() && s.charAt(index) == c) {
                count++;
                index++;
            }
            sb.append(String.valueOf(count));
            sb.append(c);
            if (index < s.length()) {
                c = s.charAt(index);
                count = 0;
            }
        }
        return sb.toString();
    }

    @Test
    public void test() {
        System.out.println(encode("112223"));
    }
}
